<template>
  <view>
    <navbar :showLeft="true" title="面试历史" @leftClick="handleBack"></navbar>
    <view class="header" :style="{paddingTop: appInfoStore.getInfo().navBarHeight + 2*appInfoStore.getInfo().statusBar + 'px'}"></view>

    <view class="history-page">
      <view class="content-wrapper">

        <view class="history-list">
          <view v-if="dataSource">
            <view
              v-for="item in dataSource"
              :key="item.id"
              class="history-item"
              @click="handleItemClick(item)"
            >
              <view class="item-header">
                <view class="interview-type">{{ item.title }}</view>
                <view class="score" :class="{ 'no-score': item.score === '--' }">
                  得分: {{ item.score||'--' }}
                </view>
              </view>
              <view class="time">{{ formatTime(item.startTime) }}</view>
            </view>

            <button class="clear-btn" @click="handleClearHistory">
              清除所有历史记录
            </button>
          </view>

          <view v-else class="empty-state">
            <uni-icons type="info" size="64" color="#ccc"></uni-icons>
              <view class="empty-text">暂无面试记录</view>
            <button class="start-btn" @click="startNewInterview">开始新面试</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
const appInfoStore = useAppInfoStore();
import { useAppInfoStore } from "@/stores/appInfo";
import { onLoad } from "@dcloudio/uni-app";
import { ref, getCurrentInstance } from "vue"
const { proxy } = getCurrentInstance();
import { LOCAL_STORAGE_KEY } from "@/utils/Constants.js";

const dataSource = ref([]);

// 返回按钮
const handleBack = () => {
  uni.navigateBack();
};

// 开始新面试
const startNewInterview = () => {
  uni.switchTab({
    url: '/pages/category/CategoryIndex'
  });
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '未知时间';
  try {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${padZero(date.getMonth()+1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
  } catch (e) {
    console.warn('时间格式化错误:', e);
    return timestamp;
  }
};

const padZero = (num) => num.toString().padStart(2, '0');


// 加载历史数据
const loadDataList = async () => {
  uni.request({
    url: proxy.Api.domain+proxy.Api.getHistoryInterview, // 确保URL正确
    method: 'GET',
    header:{
      'token': uni.getStorageSync(LOCAL_STORAGE_KEY.token.key),
    },
    success: (res) => {
      console.log("原生请求结果:", res);
      // 实际数据可能在 res.data 中
      dataSource.value = res.data.rows
    },
    fail: (err) => {
      console.error("请求失败:", err);
    }
  });
};

// 点击面试项
const handleItemClick = (item) => {
  if (item.interviewId) {
    uni.navigateTo({
      url: `/pages/report/InterviewReport?interviewId=${item.interviewId}`
    });
  }
};


// 清除历史记录
const handleClearHistory = async () => {
  uni.showModal({
    title: '提示',
    content: '确定要清除所有历史记录吗？此操作不可恢复',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
            mask: true
          });
          
          // 调用删除接口
          const result = await proxy.Request({
            url: proxy.Api.deleteHistory,
            method: 'POST',
            showLoading: false
          });
          
          if (result) {
            dataSource.value = [];
            uni.showToast({
              title: '历史记录已清除',
              icon: 'success'
            });
          }
        } catch (error) {
          console.error('删除失败:', error);
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

onLoad(() => {
  loadDataList();
});
</script>

<style scoped>
/* 页面基础样式 */
.history-page {
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 内容容器 */
.content-wrapper {
  margin: 8px;
  border-radius: 8px;
  padding: 16px;
}

/* 面试历史标题 */
.history-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

/* 面试历史列表 */
.history-list {
  margin-bottom: 18px;
}

/* 历史记录项 */
.history-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-item:active {
  background-color: #f0f0f0;
  transform: scale(0.98);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.interview-type {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.score {
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
}

.score.no-score {
  color: #999;
}

.question-tag {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.5;
  word-break: break-word;
}

.time {
  font-size: 12px;
  color: #999;
}

/* 清除按钮样式 */
.clear-btn {
  width: 100%;
  padding: 12px;
  border-radius: 8px;
  background-color: transparent;
  color: #ff4d4f;
  border: 1px solid #ff4d4f;
  cursor: pointer;
  font-size: 14px;
  margin-top: 16px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-image {
  width: 200px;
  height: 200px;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin-bottom: 20px;
}

.start-btn {
  width: 60%;
  padding: 12px;
  border-radius: 8px;
  background-color: #0282ee;
  color: #fff;
  border: none;
  font-size: 16px;
}
</style>